package com.study.service.impl;

import com.alibaba.fastjson.JSON;
import com.study.bean.UserInfoTo;
import com.study.bean.car.CartItem;
import com.study.interceptor.CarInterceptor;
import com.study.service.CarService;
import com.study.vo.Car;
import com.study.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CarServiceImpl implements CarService {

    @Autowired
    StringRedisTemplate redisTemplate;

    private final String CART_PREFIX = "shop:car:";

    @Override
    public CartItem addToCar(Long skuid, Integer num) {
        BoundHashOperations<String, Object, Object> carOps = getCarOps();

        //2 添加新商品到 购物车
        CartItem cartItem = new CartItem();
        //如果购物车已经存在此商品
        String o = (String) carOps.get(skuid.toString());
        if (!StringUtils.isEmpty(o)) {
            // 修改 购物车中商品数量
            cartItem = JSON.parseObject(o, CartItem.class);
            cartItem.setCount(cartItem.getCount() + num);
            carOps.put(skuid.toString(), JSON.toJSONString(cartItem));
        } else {
            //1 查询要添加的商品信息
            SkuInfoVo skuInfoVo = selectBySkuId(skuid);
            cartItem.setCheck(true);
            cartItem.setCount(num);

            cartItem.setImage(skuInfoVo.getImage());
            cartItem.setTitle(skuInfoVo.getSkuDesc());
            cartItem.setSkuId(skuid);
            cartItem.setPrice(skuInfoVo.getPrice());

            // 3 查询 SHU组合信息

            List<String> skuattr = new ArrayList<>();
            skuattr.add("a");
            skuattr.add("b");
            skuattr.add("c");
            cartItem.setSkuAttr(skuattr);

            carOps.put(skuid.toString(), JSON.toJSONString(cartItem));
        }
        return cartItem;
    }

    @Override
    public Car getCar() {
        //1 判断状态。
        UserInfoTo userInfoTo = CarInterceptor.localUser.get();
        Car car = new Car();
        if (userInfoTo.getUserId() != null) {
            //1登录了
            String carKey = CART_PREFIX + userInfoTo.getUserId();
            //如果临时购物车的数据还没有合并，合并起来。并清空临时购物车
            String tempCarKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> tempCartItems = getCartItems(tempCarKey);

            // 2TODO 集合判断是否为空
            if (!CollectionUtils.isEmpty(tempCartItems)) {
                //临时购物车有数据，需要合并
                for (CartItem cartItem : tempCartItems) {
                    addToCar(cartItem.getSkuId(), cartItem.getCount());
                }
                //清空临时购物车
                clearCart(tempCarKey);
            }
            // 3 获取登录后的购物车|包含临时购物车合并过来的内容F
            List<CartItem> cartItems = getCartItems(carKey);
            car.setItems(cartItems);

        } else {
            //没登录
            String carKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> cartItems = getCartItems(carKey);
            car.setItems(cartItems);
        }

        return null;
    }

    @Override
    public void clearCart(String cartkey) {
        redisTemplate.delete(cartkey);
    }

    @Override
    public List<CartItem> getUserCarItems() {
        UserInfoTo userInfoTo = CarInterceptor.localUser.get();
        if (userInfoTo.getUserId() == null) {
            return null;
        } else {
            String carKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> cartItems = getCartItems(carKey);
            //获取选中的 购物项
            List<CartItem> collect = cartItems.stream().
                    filter(item -> item.isCheck())
                    .map(cartItem -> {
                        //TODO 查询最新价格
                        cartItem.setPrice(new BigDecimal(2).multiply(cartItem.getPrice()));
                        log.info("skuId={}|最新价格为{}", cartItem.getSkuId(), cartItem.getPrice());
                        return cartItem;
                    })
                    .collect(Collectors.toList());
            return collect;
        }
    }

    /**
     * 模拟查询 数据库
     *
     * @param skuid
     * @return
     */
    private SkuInfoVo selectBySkuId(Long skuid) {
        SkuInfoVo skuInfoVo = new SkuInfoVo();
        skuInfoVo.setSkuId(skuid).setImage("1.jpg")
                .setSkuDesc("desc");
        return skuInfoVo;
    }

    /**
     * 获取到要操作的购物车
     *
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCarOps() {
        ThreadLocal<UserInfoTo> localUser = CarInterceptor.localUser;
        UserInfoTo userInfoTo = localUser.get();

        //car:userid作为redis购物车ID
        String carKey = "";
        if (userInfoTo.getUserId() != null) {
            //登录购物车
            carKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            carKey = CART_PREFIX + userInfoTo.getUserKey();//临时购物车
        }
        //判断当前购物车 是否存在此商品|绑定一个购物车，接下来的 操作都是 操作同一个key
        BoundHashOperations<String, Object, Object> boundHashOps = redisTemplate.boundHashOps(carKey);
        return boundHashOps;
    }

    /**
     * 根据KEY 获取购物车
     *
     * @param carKey
     * @return
     */
    private List<CartItem> getCartItems(String carKey) {

        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(carKey);
        List<Object> values = hashOps.values();
        if (values != null && values.size() > 0) {
            List<CartItem> collect = values.stream().map(obj -> {
                String str = (String) obj;
                return JSON.parseObject(str, CartItem.class);
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }


}
